package com.itheima.bos.web.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.bos.domain.take_delivery.Promotion;
import com.itheima.bos.service.PromotionService;
import com.itheima.bos.web.action.common.BaseAction;

@ParentPackage(value = "json-default")
@Namespace("/promotion")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {

	@Autowired
	private PromotionService promotionService;

	// 文本编辑器上传图片
	private File imgFile;

	private String imgFileFileName;

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	@Action(value = "image_upload", results = { @Result(name = "success", type = "json") })
	public String image_upload() {
		// 文件保存目录路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";

		// 文件保存目录URL
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

		String randomFileName = UUID.randomUUID().toString();
		String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
		try {
			File destFile = new File(savePath + "/" + randomFileName + ext);
			FileUtils.copyFile(imgFile, destFile);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("error", 0);
		map.put("url", savePath + "/" + randomFileName + ext);
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}

	@Action(value = "image_manager", results = { @Result(name = "success", type = "json") })
	public String image_manager() {
		// 文件保存目录路径
		String rootPath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";

		// 文件保存目录URL
		String rootUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";
		//图片扩展名
		String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

		//根据path参数，设置各路径和URL
		String path = ServletActionContext.getRequest().getParameter("path") != null ? ServletActionContext.getRequest().getParameter("path") : "";
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		//排序形式，name or size or type
		String order = ServletActionContext.getRequest().getParameter("order") != null ?  ServletActionContext.getRequest().getParameter("order").toLowerCase() : "name";

		//目录不存在或不是目录
		File currentPathFile = new File(currentPath);

		//遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if(currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if(file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if(file.isFile()){
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}

		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

		ServletActionContext.getContext().getValueStack().push(result);
		
		return SUCCESS;
	}
	//表单上传图片
	private File titleImgFile;
	
	private String titleImgFileFileName;
	
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	@Action(value="promotion_save",results={@Result(name="success",type="redirect",location="../pages/take_delivery/promotion.html")})
	public String promotion_save(){
		// 文件保存目录路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";

		// 文件保存目录URL
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

		String randomFileName = UUID.randomUUID().toString();
		String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		try {
			File destFile = new File(savePath + "/" + randomFileName + ext);
			FileUtils.copyFile(titleImgFile, destFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.setTitleImg(saveUrl + randomFileName + ext);
		promotionService.save(model);
		return SUCCESS;
	}
	
	@Action(value="promotion_pageQuery",results={@Result(name="success",type="json")})
	public String promotion_pageQuery(){
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Promotion> page = promotionService.findAll(pageable);
		ServletActionContext.getContext().getValueStack().push(page);
		return SUCCESS;
	}
}
